<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Validator;

use Laminas\Session\Container;
use Laminas\Validator\AbstractValidator;

class PhoneCaptchaValidator extends AbstractValidator
{
    const NOT_SCALAR    = 'notScalar';
    const ERROR_PHONE   = 'errorPhone';
    const ERROR_CAPTCHA = 'errorCaptcha';

    private $dbshopSession;

    protected $messageTemplates = [
        self::NOT_SCALAR    => "这不是一个标准输入值",
        self::ERROR_PHONE   => "手机号码与获取验证码的手机号码不同",
        self::ERROR_CAPTCHA => "验证码错误"
    ];

    public function __construct($options = null)
    {
        $this->dbshopSession = new Container('dbshopSession');

        parent::__construct($options);
    }

    public function isValid($value, $context=null)
    {
        if(!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        if (empty($context['userPhone']) || !$this->dbshopSession->offsetExists('phoneNumber') || ($this->dbshopSession->offsetExists('phoneNumber') && $this->dbshopSession->offsetExists('phoneNumber') != $context['userPhone'])) {
            $this->error(self::ERROR_PHONE);
            return false;
        }

        if (!$this->dbshopSession->offsetExists('phoneCaptcha') || $this->dbshopSession->offsetGet('phoneCaptcha') != $value) {
            $this->error(self::ERROR_CAPTCHA);
            return false;
        }

        return true;
    }
}